import math
import pygame
from pieces import calculate_intersection, modify_piecesstatus, getposiempty, getposselected, checkfinish

pygame.display.set_caption("Solitaire Game")

class Button:
    def __init__(self, text, position):
        self.text = text
        self.position = position
        self.font = pygame.font.Font(None, 36)
        self.rect = pygame.Rect(position[0], position[1], 36, 39)

    def draw(self, surface):
        pygame.draw.rect(surface, (199, 199, 199), self.rect)
        text_surface = self.font.render(self.text, True, (0, 0, 0))
        surface.blit(text_surface, (self.position[0] + 10, self.position[1] + 9))

    def is_clicked(self, pos):
        if self.rect.collidepoint(pos):
            return True
        return False

class Game:
    def __init__(self):
        self.done = False
        self.won = False
        self.piecespos = []
        
        pygame.init()

        screen_info = pygame.display.Info()
        self.size = (screen_info.current_w, screen_info.current_h)
        width, height = self.size
        self.piecesize = min(width, height) / 10

        self.green = (0, 155, 0)
        self.black = (0, 0, 0)
        self.white = (255, 255, 255)
        self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)

        # 创建按钮实例
        self.close_button = Button("X", (10, 10))

    def run_game(self):
        pygame.init()

        width, height = self.size
        radius = min(width, height) * 0.9 / 2
        self.piecesize = radius / 10

        self.piecespos = self.draw_board(radius)

        pygame.display.flip()

        while not self.done:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.done = True
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        pos = self.get_clicked_position()
                        print(pos)
                        if pos != -1:
                            modify_piecesstatus( pos )
#                            if checkfinish(): return
            self.draw_board(radius)
            pygame.display.flip()

    def get_clicked_position(self):
        mouse_pos = pygame.mouse.get_pos()

        # 检查按钮是否被点击
        if self.close_button.is_clicked(mouse_pos):
            print( "close X" )
            pygame.quit()
            sys.exit()

#        for i, point in enumerate(self.pieces):
#            print( i, point[0], point[1] )
        for i, point in enumerate(self.piecespos):
            x, y = int(point[0]), int(point[1])
            print( x, y )
            distance = ((mouse_pos[0] - x) ** 2 + (mouse_pos[1] - y) ** 2) ** 0.5
            if distance <= self.piecesize:
                return i
        return -1  # 如果没有点击在任何圆内，则返回-1表示无效点击

    def draw_board(self, radius):
        self.screen.fill(self.green)

        star_points = []
        intersection_points = []

        angle = math.radians(360 / 5)

        width, height = self.size
        for i in range(5):
            x = radius * math.cos(i * angle - math.radians(90))
            y = radius * math.sin(i * angle - math.radians(90))
            star_points.append((width/2 + x, height/2 + y, self.white, i))

        for i in range(5):
            pygame.draw.line(self.screen, self.black, star_points[i][:2], star_points[(i + 2) % 5][:2], 3)

        for i in range(5):
            intersection_segment = [star_points[i][:2], star_points[(i + 2) % 5][:2]]
            intersection = calculate_intersection(intersection_segment, [star_points[(i + 1) % 5][:2],
                                                                           star_points[(i + 3) % 5][:2]])
            if intersection is not None:
                intersection_points.append(intersection)

        piecesize = int(self.piecesize)

        tmpidx = 0

        for point in star_points:
            x = int(point[0])
            y = int(point[1])
            if getposiempty( tmpidx ):
                if getposselected(tmpidx):
                    color = self.white
                else:
                    color = self.black
                pygame.draw.circle(self.screen, color, (x, y), piecesize, 1)
            tmpidx += 1

        for point in intersection_points:
            x = int(point[0])
            y = int(point[1])
            if getposiempty( tmpidx ):
                if getposselected(tmpidx):
                    color = self.white
                else:
                    color = self.black
                pygame.draw.circle(self.screen, color, (x, y), piecesize, 1)
            tmpidx += 1

        ret = star_points + intersection_points

        font = pygame.font.Font(None, 60)
        for i, point in enumerate(ret):
            index_text = font.render(str(i), True, pygame.Color("red"))
            self.screen.blit(index_text, (point[0], point[1]))

        self.close_button.draw(self.screen)
        return ret

    def main(self):
        self.run_game()
        pygame.quit()

if __name__ == "__main__":
    game = Game()
    game.main()